<template>
  <div class="company-definite">
    <el-row class="company-title" :gutter="20">
      <el-col :span="21" />
      <el-col :span="2" class="right">
        <el-button v-if="!readOnly" icon="el-icon-plus" :disabled="addDis" size="mini" @click="handleAddTableFromData">新增</el-button>
      </el-col>
    </el-row>
    <el-form ref="tableForm" inline-message :model="formTableData" :rules="tableRules">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        class="definite-list"
        :data="tableFormData"
        :size="detailSize"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column column-key="2" type="index" label="序号" width="65" align="center" />
        <el-table-column
          prop="fieldName"
          label="字段名称"
          min-width="120"
          align="center"
          column-key="3"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.action == 'view' || scope.row.action == 'fill'">{{ scope.row.fieldName }}</span>
            <el-form-item v-else prop="fieldName">
              <el-input v-model="formTableData.fieldName" :readonly="readOnly" clearable placeholder="请输入字段名称" @input="translateFieldName($event)" />
            </el-form-item>
          </template>
        </el-table-column>
        <!--<el-table-column
          prop="fileVal"
          label="字段值"
          min-width="120"
          align="center"
          column-key="3"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.action == 'view' || scope.row.action == 'fill'">{{ scope.row.fileVal }}</span>
            <el-form-item v-else prop="fileVal">
              &lt;!&ndash;              <el-input v-model="formTableData.fileVal" :readonly="readOnly" clearable placeholder="请输入英文" />&ndash;&gt;
              <el-select
                v-model="formTableData.fileVal"
                :readonly="readOnly"
                clearable
                filterable
                allow-create
                default-first-option
                style="width: 100%"
                placeholder="请选择或者输入英文"
              >
                <el-option
                  v-for="item in certificateEnList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>-->
        <el-table-column
          prop="fileVal"
          label="是否定时提醒"
          min-width="120"
          align="center"
          column-key="3"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.action == 'view' || scope.row.action == 'fill'">{{ scope.row.isRemind === '0' ? '是': '否' }}</span>
            <el-form-item v-else prop="fileVal">
              <el-radio-group v-model="formTableData.isRemind" :readonly="readOnly">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!readOnly" column-key="10" prop="operation" label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="scope.row.action=== 'add'" size="mini" @click="click_add(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="scope.row.action=== 'add'" size="mini" @click="cancelAdd(scope.row,scope.$index)">取消</el-button>
            <el-button v-if="scope.row.action=== 'edit'" size="mini" @click="click_editSave(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="scope.row.action=== 'edit'" size="mini" @click="cancelEdit(scope.row,scope.$index)">取消</el-button>
            <el-button v-if="scope.row.action=== 'view'" size="mini" @click="click_edit(scope.row,scope.$index)">修改</el-button>
            <el-button v-if="scope.row.action=== 'view' && scope.row.existing !== true" size="mini" @click="deleteRow(scope.row,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
// 字段审核
import { validateNumLetter } from '@/utils/validate'
// 系统字典
import { getSysDicts } from '@/api/common/getSysDicts' // 查询字典类行中的数据
import pinyin from 'js-pinyin'
export default {
  name: 'CompanyDefinite',
  props: {
    companyTitle: {
      type: String,
      default: ''
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    tableData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    const checkLength = (rule, value, callback) => {
      if (value.length > 6) {
        callback('字段值长度不得超出6位')
      } else {
        callback()
      }
    }
    return {
      certificateEnList: [],
      // 明细表
      addDis: false, // 新增按钮是否可用
      formTableData: {
        fieldName: '',
        fileVal: '',
        isRemind: '1'
      }, // 每一行的表单
      tableFormData: this.tableData, // 表格
      loading: false,
      tableRules: {
        fieldName: [
          { required: true, message: '字段值名称不得为空', trigger: 'blur' },
          { required: true, validator: checkLength, trigger: 'blur' }
        ],
        fileVal: [
          { required: true, message: '字段名不得为空' },
          { required: true, validator: validateNumLetter, trigger: 'blur', message: '请输入正确的类型' }
        ]
      }, // 表格验证
      deleteDetail: []
    }
  },
  watch: {
    tableData(val) {
      let newArr = []
      if (val && val.length > 0 && val[0].oldRow === undefined && val[0].action !== 'view') {
        newArr = val.map(item => {
          if (item.fieldName === '无') {
            this.addDis = true
          }
          item.action = 'view'
          return item
        })
      } else {
        newArr = val
      }
      if (JSON.stringify(val) !== JSON.stringify(this.tableFormData)) {
        this.tableFormData = newArr
      }
    },
    tableFormData: {
      handler(newVal) {
        this.changetableFormData()
      },
      deep: true
    }
  },
  mounted() {
    this.getcertificate()
  },
  methods: {
    // 翻译字段名称
    translateFieldName(e) {
      this.formTableData.fileVal = pinyin.getFullChars(e).length > 20 ? pinyin.getCamelChars(e) : pinyin.getFullChars(e)
    },
    // 获取证书字段英文名
    getcertificate() {
      getSysDicts('sys_certificate_filed').then(res => {
        if (res) {
          this.certificateEnList = res.data.rows
        } else {
          this.msgError(res.message)
        }
      })
    },
    /** ****** 动态新增表格start****************/
    // 判断存在表格是否可编辑
    filterTableFromDataEdit(tableFromData) {
      let flg = false
      this.tableFormData.map(item => {
        if (item.action === 'add' || item.action === 'edit') {
          flg = true
        }
      })
      return flg
    },
    // 动态表格新增一行
    handleAddTableFromData() {
      if (this.tableFormData && this.tableFormData.length > 0) {
        if (this.filterTableFromDataEdit(this.tableFormData)) {
          this.msgInfo('请先保存正在编辑的数据')
        } else {
          this.tableFormData.push({
            action: 'add',
            oldRow: {}
          })
          this.addDis = true
        }
      } else {
        this.tableFormData = []
        this.tableFormData.push({
          action: 'add',
          oldRow: {}
        })
        this.addDis = true
      }
    },
    // 判断新增按钮是否可用
    checkAddBtn(tableFormData) {
      if (tableFormData.length > 0) {
        this.addDis = false
        tableFormData.map((item) => {
          if (item.action === 'add' || item.action === 'edit') {
            this.addDis = true
            return
          }
        })
      } else {
        this.addDis = false
      }
    },
    // 判断明细不能重复
    checkRepeat(tableFormData, row, index) {
      if (tableFormData.length > 0) {
        for (let i = 0; i < tableFormData.length; i++) {
          if (tableFormData[i].fieldName === row.fieldName && tableFormData[i].fileVal === row.fileVal && i !== index) {
            this.msgInfo('不能填写重复的字段')
            tableFormData[index].action = 'add'
            return false
          }
        }
        tableFormData[index].action = 'view'
        this.checkAddBtn(tableFormData)
      }
    },
    // 检查表单是否为无
    checkcertLabelNull(fieldName, fileVal, isRemind, row, index) {
      this.formTableData = {
        fieldName,
        fileVal,
        isRemind
      }
      this.tableFormData[index] = Object.assign(this.tableFormData[index], this.formTableData)
      this.checkRepeat(this.tableFormData, row, index)
      this.emptyFormData()
    },
    // 新增保存操作
    click_add(row, index) {
      this.$refs.tableForm.validate(validate => {
        if (validate) {
          this.checkcertLabelNull(this.formTableData.fieldName, this.formTableData.fileVal, this.formTableData.isRemind, row, index)
        }
      })
    },
    // 新增取消
    cancelAdd(row, index) {
      this.emptyFormData()
      this.tableFormData.splice(index, 1)
      this.checkAddBtn(this.tableFormData)
    },
    // 修改保存
    click_editSave(row, index) {
      console.log(typeof this.formTableData.fieldName)
      this.$refs.tableForm.validate(validate => {
        if (validate) {
          this.checkcertLabelNull(this.formTableData.fieldName + '', this.formTableData.fileVal, this.formTableData.isRemind, row, index)
        }
      })
    },
    // 修改取消
    cancelEdit(row, index) {
      this.$set(this.tableFormData, index, row)
      row.action = 'view'
      this.checkAddBtn(this.tableFormData)
      this.emptyFormData()
    },
    // 修改
    click_edit(row, index) {
      if (!this.isReadOnly) {
        if (this.filterTableFromDataEdit(this.tableFormData)) {
          this.msgInfo('请先保存正在编辑的数据')
        } else {
          row.action = 'edit'
          // 将原数据放到oldRow对象中
          row.oldRow = JSON.parse(JSON.stringify({ ...row }))
          this.formTableData = { ... row }
          this.$set(this.tableFormData, index, row)
          this.checkAddBtn(this.tableFormData)
        }
      }
    },
    // 删除
    deleteRow(row, index) {
      this.tableFormData.splice(index, 1)
      if (row.id !== '') {
        this.deleteDetail.push(row.id)
      }
      this.emptyFormData()
      this.checkAddBtn(this.tableFormData)
    },
    // 清空 动态表格
    emptyFormData() {
      this.resetForm('tableForm')
      this.formTableData.id = ''
      this.formTableData.fieldName = ''
      this.formTableData.fileVal = ''
      this.formTableData.isRemind = '1'
    },
    // 把信息回传给父组件
    changetableFormData() {
      this.$emit('getTableFormData', this.tableFormData)
    }
    /** 动态新增表格end******************/
  }
}
</script>

